package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层
 */
@RequestMapping("/depts")
@RestController //@Controller + @ResponseBody
@Slf4j
//@CrossOrigin //解决跨域  容许跨域访问
public class DeptController {

    //注入业务层
    @Autowired
    private DeptService deptService;

    /**
     * 查询所有部门
     *
     * @return
     */
    @GetMapping
    public R list() {
        log.info("查询所有部门");
        //调用业务层查询数据
        List<Dept> list = deptService.list();
        //返回结果
        return R.ok(list);
    }

    /**
     * 添加部门
     *
     * @param dept
     * @return
     */
    @PostMapping
    public R add(@RequestBody Dept dept) {
        log.info("添加部门:{}", dept);
        deptService.add(dept);
        return R.ok();
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {
        log.info("根据id查询：{}", id);
        Dept dept = deptService.getById(id);
        return R.ok(dept);
    }

    /**
     * 根据id修改
     *
     * @param dept
     * @return
     */
    @PutMapping
    public R update(@RequestBody Dept dept) {
        log.info("根据id修改：{}", dept);
        deptService.updateById(dept);
        return R.ok();
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Integer id) {
        log.info("根据id删除：{}", id);
        deptService.deleteById(id);
        return R.ok();
    }
}
